/**
 * /admin/student/add
 * 
 * 新增用户
 */

const User_info = require('../../../models/usersInfo')
const Users = require('../../../models/users')
const utils = require('../../../utils/index')
const MySQLManager = require('../../../utils/MySQLManager');
const sequelize = MySQLManager
const $ = require('../../../utils/common')

const add_students = async function (req, res) {
  try {
      // 参数检查
      if (!req.body.students) {
        $.sendMessage(res, 1015, '参数students没有传')
        return
    }
  
    // 事务
    return sequelize.transaction(function (t) {
        students = req.body.students      
        return Users.bulkCreate(
            students,
            {updateOnDuplicate:["user_name"]}
        , 
        {transaction: t}).then(function (user) {
          return User_info.bulkCreate(
            students,
            {updateOnDuplicate:["user_name"]}
            , {transaction: t});
        });
      
      }).then(function (result) {
          res.json({
              code: 200,
              message: '导入成功',
            //   result: result
          })
        // 事务已被提交
        // result 是 promise 链返回到事务回调的结果

        // // 日志
        utils.create_a_log(req, '学生列表', '导入')
        return
      }).catch(function (err) {
          res.json({
              code: 1017,
              message: '导入失败',
              err: 'err' + err
          })
        // 事务已被回滚
        // err 是拒绝 promise 链返回到事务回调的错误
      });
  }
  catch(error) {
    $.sendMessage(res, 1015, 'error' + error)
    return
  }
    
}
    
module.exports = add_students